﻿//-----------------------------------------------------------------------
// <copyright file="MLSharePointSqlSession.cs" company="MAPILab Ltd">
//     Copyright (c) MAPILab Ltd.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace MAPILab.SharePoint.Explorer.Utilities
{
    using System;
    using System.Data.SqlClient;
    using System.Reflection;
    using Microsoft.SharePoint.Administration;

    /// <summary>
    /// Class for work with SQL database (execute information)
    /// </summary>
    class MLSharePointSqlSession
    {
        #region Fields

        /// <summary>
        /// Type of SQL session
        /// </summary>
        private static Type typeSqlSession;

        /// <summary>
        /// Full name of type
        /// </summary>
        const string typeNameSqlSession = "Microsoft.SharePoint.Utilities.SqlSession";

        /// <summary>
        /// SQL session
        /// </summary>
        private object sqlSession;

        #endregion

        #region Constructors

        /// <summary>
        /// Default constructor
        /// </summary>
        public MLSharePointSqlSession()
        {
            typeSqlSession = typeof(SPFarm).Assembly.GetType(typeNameSqlSession);
        }

        /// <summary>
        /// Constructor with custom connection string
        /// </summary>
        /// <param name="connectionString"></param>
        public MLSharePointSqlSession(string connectionString)
            : this()
        {
#if Explorer
            sqlSession = Activator.CreateInstance(typeSqlSession, connectionString);
#else
            sqlSession = Activator.CreateInstance(typeSqlSession, new object[] { connectionString, null });
#endif
        }

        #endregion

        #region Methods

        /// <summary>
        /// Execute reader from sql session
        /// </summary>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public SqlDataReader ExecuteReader(SqlCommand sqlCommand)
        {
            MethodInfo mi = typeSqlSession.GetMethod("ExecuteReader", new Type[] { typeof(SqlCommand) });
            return mi.Invoke(sqlSession, new object[] { sqlCommand }) as SqlDataReader;
        }

        /// <summary>
        /// Execute non query from sql session
        /// </summary>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public int ExecuteNonQuery(SqlCommand sqlCommand)
        {
            MethodInfo mi = typeSqlSession.GetMethod("ExecuteNonQuery", new Type[] { typeof(SqlCommand) });
            return (int)mi.Invoke(sqlSession, new object[] { sqlCommand });
        }

        #endregion
    }
}
